<?php

namespace app\mini\controller\salesman;

use app\common\controller\ApiController;
use app\common\model\SalesmanDealer;
use app\common\model\SalesmanStore;
use app\common\model\SignIn;
use app\common\model\Store as StoreModel;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\company\model\CompanyOrder;
use app\company\model\DealerStore;
use app\Request;
use Carbon\Carbon;
use think\App;
use think\db\exception\DbException;
use think\response\Json;
use app\common\enum\mini\Store as  StoreEnum;

/**
 * @ControllerAnnotation (title="门店相关")
 */

class Store extends ApiController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new StoreModel();
        $this->joinTable = 'region,salesman';
    }

    /**
     * @throws DbException
     */
    public function list(): Json
    {
        $get = $this->request->get();
        $today = Carbon::now();
        $where = [];
        if(!empty($get['type']) && $get['type'] == StoreEnum::TODAY){
            $start = strtotime(date('Y-m-d 00:00:00', time()));
            $end = strtotime(date('Y-m-d 23:59:59', time()));
            $orderIds = CompanyOrder::where('create_time','between',[$start,$end])->group('store_id')->column('store_id');
            $where[] = ['vk_store.id','in',$orderIds];
        }
        if(!empty($get['name'])){
            $where[] = ['name','like','%'.$get['name'].'%'];
        }
        if(!empty($get['lng']) && !empty($get['lat'])){
            $distance = distance($get['lng'],$get['lat']);
        }else{
            $distance = "'位置未知' AS distance";
        }
        $field = "*,{$distance}";
        $list = $this->model->field($field)->with(['salesman','dealer'])->order('distance');
        if($this->userInfo['scene_id'] == 2){
            $list = $list->hasWhere('salesman',function ($query) {
                $query->where('salesman_id', $this->uid);
            });
        }else{
            $list = $list->hasWhere('dealer',function ($query) {
                $query->where('dealer_id', $this->uid);
            });
        }
        $list = $list->where($where)->paginate($get['limit'] ?? 15)->each(function ($item) use ($today){
            $lastOrderDate = CompanyOrder::where('store_id', $item['id'])->order('id desc')->value('create_time');
            if($lastOrderDate){
                $day = date("Y-m-d", $lastOrderDate);
                if($today->diffInDays($day)){
                    $item->last_date = $today->diffInDays($day).'天前';
                }else{
                    $item->last_date = '今日';
                }
            }else{
                $item->last_date = '未下单';
            }
            $item->is_sign = 1;// 默认未签到=1，已签到=2
            $item->is_sign_text = '未签到';// 默认未签到=1，已签到=2
            $item->sign_time = '';// 默认未签到=1，已签到=2
            $start = strtotime(date('Y-m-d 00:00:00', time()));
            $end = strtotime(date('Y-m-d 23:59:59', time()));
            $signIn = (new SignIn())
                ->where('store_id', $item['id'])
                ->where('salesman_id',$this->uid)
                ->where('create_time', 'between', [$start,$end])->find();
            if($signIn){
                $item->is_sign = 2;// 默认未签到=1，已签到=2
                $item->is_sign_text = '已签到';// 默认未签到=1，已签到=2
                $item->sign_time = $signIn['create_time'];// 默认未签到=1，已签到=2
            }
        })->toArray();
        return $this->success($list);
    }

    /**
     * @NodeAnnotation(title='业务员门店签到')
     * @param Request $request
     * @return Json
     * @throws \app\common\exception\BaseException
     */
    public function signIn(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        if(empty($post['store_id'])){
            return $this->error('门店ID缺失！');
        }
        $storeInfo = (new SalesmanStore())->where('store_id',$post['store_id'])->where('salesman_id',$this->uid)->find();
        if(!$storeInfo){
            return $this->error('这不是你负责的门店，没有权利签到！');
        }
        $data = [
            'salesman_id' => $this->uid,
            'store_id' => $post['store_id'],
            'lon' => $post['lon'] ?? '',
            'lat' => $post['lat'] ?? '',
            'remark' => $post['remark'] ?? '',
        ];
        (new SignIn())->save($data);
        return $this->success('签到成功！');
    }

    /**
     * @NodeAnnotation(title='业务员门店签到记录')
     * @return Json
     * @throws DbException
     */
    public function signLog(): Json
    {
        $get = $this->request->get();
        if(empty($get['store_id'])) return $this->error('门店ID缺失！');
        $list = (new SignIn())
            ->where('salesman_id',$this->uid)
            ->where('store_id',$get['store_id'])
            ->order('id','desc')
            ->paginate($get['limit']??10);
        return $this->success($list);
    }


    public function add(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $this->sceneValidate($post, 'add');
        $post['company_id'] = $this->companyId;
        // 获取当前业务员绑定的经销商
        $dealer_id = SalesmanDealer::where('salesman_id',$this->uid)->value('dealer_id');
        try {
            $this->model->transaction(function () use ($post,$dealer_id)
            {
                $this->model->save($post);
                // 门店绑定经销商
                (new DealerStore())->save([
                    'dealer_id' => $dealer_id,
                    'store_id' => $this->model->id,
                    'company_id' => $this->companyId
                                          ]);
                // 门店绑定经销商下所有的业务员
                $salesmanIds = (new SalesmanDealer())->where('dealer_id',$dealer_id)->column('salesman_id');
                $addArr = [];
                foreach ($salesmanIds as $salesmanId){
                    $addArr[] = [
                            'store_id' => $this->model->id,
                            'company_id' => $this->companyId,
                            'salesman_id' => $salesmanId
                    ];
                }
                (new SalesmanStore())->saveAll($addArr);
            });
        } catch (\Exception $e) {
            return $this->error('新增失败:' . $e->getMessage());
        }
        return $this->success('新增成功');
    }

    public function edit(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $rule = [
                'id' => 'require|integer'
        ];
        $this->validate($post, $rule);
        $row = $this->model->find($post['id']);
        if (!$row) return $this->error('数据不存在！');
        try {
            $this->model->transaction(function () use ($post, $row)
            {
                $row->save($post);
            });
        } catch (\Exception $e) {
            return $this->error('保存失败:' . $e->getMessage());
        }
        return $this->success('保存成功');
    }
}